package com.zhmsky.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhmsky.entity.User;
import com.zhmsky.mapper.UserMapper;
import com.zhmsky.model.ResultMap;
import com.zhmsky.service.UserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author zhmsky
 * @date 2021/12/5 20:04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ResultMap resultMap;

    @Autowired
    private UserMapper userMapper;


    @GetMapping("/getUserByName")
    public ResultMap getUserByName(@RequestParam("username") String username){
        User user = userMapper.getUserByName(username);
        if(user!=null){
            return resultMap.success().code(200).message(user);
        }else{
            return resultMap.fail().code(400).message("该用户不存在！");
        }
    }

    /**
     * @description user和admin角色可以修改密码
     * @param username 用户名
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return
     */
    @GetMapping("/updatePassword")
    @RequiresRoles(logical = Logical.OR, value = {"user", "admin"})
    public ResultMap updatePassword(String username, String oldPassword, String newPassword) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userService.getOne(wrapper);
        if (user == null) {
            return resultMap.fail().code(401).message("用户名错误!");
        }
        //获取数据库密码
        String password = user.getPassword();
        if (!password.equals(oldPassword)) {
            return resultMap.fail().code(402).message("密码错误,请重新输入!");
        } else {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("username", username).set("password", newPassword);
            boolean b = userService.update(updateWrapper);
            if (b) {
                return resultMap.success().code(200).message("密码修改成功!");
            } else {
                return resultMap.fail().code(402).message("密码修改失败!");
            }
        }
    }

    /**
     * @description 拥有admin权限的才能访问
     * @return
     */
    @GetMapping("/getRootMessage")
    @RequiresRoles(logical = Logical.OR,value = {"admin","user"})
    @RequiresPermissions("admin")
    public ResultMap getRootMessage(){
        return resultMap.success().code(200).message("已获取超管信息!");
    }

}
